/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wap.rockvilletech.portal;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.wurfl.core.Device;
import net.sourceforge.wurfl.core.WURFLHolder;
import net.sourceforge.wurfl.core.WURFLManager;

import org.apache.log4j.Logger;

/**
 *
 * @author M Bilal
 */
@SuppressWarnings("serial")
public class DownloadCharging extends HttpServlet {
	
   private static final Logger log = Logger.getLogger(DownloadCharging.class);
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String context = getServletContext().getContextPath();
        if(context.equalsIgnoreCase("/")) { 
        	context = "";
        }
    	try {
            String contentId = request.getParameter("cntid") != null ? request.getParameter("cntid") : "";
            String contentType = request.getParameter("cntype")!=null?request.getParameter("cntype"):"";
            String catId = request.getParameter("cid") != null ? request.getParameter("cid") : "";
            
            String price = request.getParameter("price")!=null?request.getParameter("price"):"";
            String brand = request.getParameter("brand")!=null?request.getParameter("brand"):"";
            String model = request.getParameter("model")!=null?request.getParameter("model"):"";
            String ua = request.getHeader("User-Agent")!=null?request.getHeader("User-Agent"):"";
            log.debug("Request Params, cntid="+contentId+", cntype="+ contentType+", cid="+catId+", price="+price+", brand="+brand+", model="+model);
            
            if(contentId.isEmpty() || contentType.isEmpty() || catId.isEmpty() || price.isEmpty() || brand.isEmpty() || model.isEmpty() || ua.isEmpty()) {
            	log.warn("UN-AUTHORIZED ACCESS TO DOWNLOAD CONTENT");
            	response.sendRedirect(context+"/content/index.jsp?app=Bollywood");
            	return;
            }
            	
            WURFLHolder wurflHolder = (WURFLHolder) getServletContext().getAttribute("net.sourceforge.wurfl.core.WURFLHolder");
        	WURFLManager wurfl = wurflHolder.getWURFLManager();
        	Device device = wurfl.getDeviceForRequest(request);    		
            WapPortalBean wpb = new WapPortalBean(device);
            
            String strGsm = String.valueOf(System.currentTimeMillis());            
            wpb.saveDownload(contentId, strGsm, brand, model, "0");
            
            Vector vec = wpb.getContentDownloadParams(contentId, catId, contentType, strGsm);

            if (vec.size() > 0) {
            	String dloadUrl = context+"/downloader?brand="+URLEncoder.encode(brand,"UTF-8")
            		+"&model="+URLEncoder.encode(model,"UTF-8")+"&msisdn="+strGsm;
                for (int i = 0; i < vec.size(); i++) {
                    String name = vec.get(i++).toString();
                    String value = vec.get(i).toString();
                    dloadUrl = dloadUrl+"&"+name+"="+value;
                }
	            //wpb.LogPrice(contentId, catId, contentType, request.getQueryString(), price, request.getRemoteHost(), brand, model);
                log.info("redirecting to ("+dloadUrl+") for content download");
                response.sendRedirect(dloadUrl);
                return;
            }
    		
    		/*
	        response.setContentType("text/plain");
	        ServletOutputStream out = response.getOutputStream();	        
	        try {
	            String str_cid=request.getParameter("cid")!=null?request.getParameter("cid"):"";
	            String str_content_type=request.getParameter("ctype")!=null?request.getParameter("ctype"):"";
	            String str_price=request.getParameter("price")!=null?request.getParameter("price"):"";
	            String str_brand=request.getParameter("brand")!=null?request.getParameter("brand"):"";
	            String str_model=request.getParameter("model")!=null?request.getParameter("model"):"";
	            WapPortalBean wpb = new WapPortalBean();
	            wpb.LogPrice(str_cid, str_content_type, request.getQueryString(), str_price, request.getRemoteAddr(), str_brand, str_model);
	            log.debug("charging logged: ("+str_cid+", "+str_content_type+", "+request.getQueryString()+", "+str_price+", "+request.getRemoteAddr()+", "+str_brand+", "+str_model+")");
	            out.write("1".getBytes());
	        } catch(Exception e){
	            log.error("Error logging price charged: ", e);
	            out.write("0".getBytes());
	        } 
	        out.close();
	        */
    		
        } catch(Exception e){
            log.error("", e);
        }
        response.sendRedirect(context+"/content/index.jsp?app=Bollywood");
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
